<?php

/**
 * Class CartController
 *
 * @author HAU DAI
 */
class CartController extends Controller
{
    /**
     * Add product to cart
     */
	 
    public function actionAddToCart()
    {
        if (Yii::app()->request->isPostRequest) {
            if(isset($_GET['product_id']) && !empty($_GET['product_id'])){
                $productId = $_GET['product_id'];
                $cartIds = isset(Yii::app()->session[SITE_ID . '_cart']) ? Yii::app()->session[SITE_ID . '_cart'] : array();
                if(isset($cartIds[$productId])){
                    $cartIds[$productId] = $cartIds[$productId] + 1;
                }else{
                    $cartIds[$productId] = 1;
                }
                Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
                echo count($cartIds);
            }
        }
    }
	public function actionBuyNow()
    {
		if(isset($_GET['product_id']) && !empty($_GET['product_id'])){
			$productId = $_GET['product_id'];
			$cartIds = isset(Yii::app()->session[SITE_ID . '_cart']) ? Yii::app()->session[SITE_ID . '_cart'] : array();
			if(isset($cartIds[$productId])){
				$cartIds[$productId] = $cartIds[$productId] + 1;
			}else{
				$cartIds[$productId] = 1;
			}
			Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
			$this->redirect(array('checkout/cart'));
		}
    }
    /**
     * Remove product from cart
     */
	 
	 public function actionUpdateQty()
    {
        if(isset($_GET['product_id']) && isset($_GET['qty'])){
			$productId = $_GET['product_id'];
			$qty = $_GET['qty'];
			// echo $productId;
			if ( is_numeric($qty) && $qty > 0 ){
				$cartIds = isset(Yii::app()->session[SITE_ID . '_cart']) ? Yii::app()->session[SITE_ID . '_cart'] : array();
				if(array_key_exists($productId, $cartIds)){
					// echo "dd";
					$cartIds[$productId] = $qty;
					Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
					$total = 0;
					foreach ($cartIds as $id => $qty) {
						$product = Product::model()->findByPk($id);
						if (is_object($product)) {
							$total += $product->on_sale * $qty;
						}
					}
					Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
					echo $total;
				}
			}
        }
    }
	
    public function actionUpdate()
    {
        if (Yii::app()->request->isPostRequest) {
            if(isset($_GET['product_id']) && !empty($_GET['product_id'])){
                $productId = $_GET['product_id'];
				// echo $productId;
                $cartIds = isset(Yii::app()->session[SITE_ID . '_cart']) ? Yii::app()->session[SITE_ID . '_cart'] : array();
				// echo "<pre>";
				// print_r($cartIds);die;
                if(array_key_exists($productId, $cartIds)){
					// echo "dd";
                    unset($cartIds[$productId]);
					echo count($cartIds);
                }
                Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
            }
        }
    }
}